const App = getApp();
const httpRequest = require('../../utils/httpRequest.js');

Page({
  data: {
    searchKeyword: '',
    searchList: [],
    imgList: [],
    movieList: [],
    etmList: [],
    searchHistory: [],
    showSearchHistory: false,
    Token:''
  },

  onLoad() {
    const userToken = wx.getStorageSync('userToken'); 
    this.setData({
      Token:userToken
    });
    this.getMovieData();
    this.getImg1();
    this.getImg2();
    this.loadSearchHistory();
  },
  //获取swiper图片
  getImg1() {
    httpRequest.Request('GET', App.globalData.backend_add + 'api/getImg1', {}, { 'Authorization': this.data.Token }, 'imgList', 'null', this);
  },
  //获取小图标图片
  getImg2() {
    httpRequest.Request('GET', App.globalData.backend_add + 'api/getImg2', {}, { 'Authorization': this.data.Token }, 'etmList', 'null', this);
  },
  //获取电影信息
  getMovieData() {
    httpRequest.Request('GET', App.globalData.backend_add + 'api/movies', {}, { 'Authorization': this.data.Token }, 'movieList', 'null', this);
  },
  //跳转到详情页
  onHandleto(e) {
    const id = e.currentTarget.dataset.id;
    const movieData = this.data.movieList[id - 1];
    const movieid = this.data.movieList[id - 1].id;
    wx.navigateTo({
      url: '/pages/details/details',
      success: function (res) {
        const eventChannel = res.eventChannel;
        eventChannel.emit('acceptDataFromHomePage', { data: movieData });
        eventChannel.emit('acceptDataFromHomePage1', { data: movieid });
      },
    });
  },
  //跳转到大麦
  turnToOthers() {
    wx.navigateTo({
      url: '/pages/hpage/ToOthers/damai',
    });
  },
  //搜索内容更新到searchKeyword
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },
  //搜索
  onSearchConfirm(e) {
    const searchData = this.data.searchKeyword;
    this.addSearchHistory(searchData);
    this.setData({ showSearchHistory: false });
    wx.navigateTo({
      url: '/pages/search/search',
      success: function (res) {
        const eventChannel = res.eventChannel;
        eventChannel.emit('acceptDataFromHomePage2', { data: searchData });
      }
    });
  },
  //显示历史记录
  onSearchFocus() {
    this.loadSearchHistory();
    this.setData({ showSearchHistory: true });
  },
  //隐藏历史记录
  onSearchBlur() {
    this.setData({ showSearchHistory: false });
  },
  //加载历史记录
  loadSearchHistory() {
    const history = wx.getStorageSync('searchHistory') || [];
    this.setData({
      searchHistory: history
    });
  },
  //增加历史记录
  addSearchHistory(keyword) {
    let history = wx.getStorageSync('searchHistory') || [];
    if (history.indexOf(keyword) === -1) {
      history.unshift(keyword);//添加到最前面
      if (history.length > 10) {
        history.pop(); // 保持历史记录最多10条
      }
      wx.setStorageSync('searchHistory', history);
    }
  },
  //选择历史记录
  onHistoryItemTap(e) {
    const keyword = e.currentTarget.dataset.item;
    this.setData({
      searchKeyword: keyword,
      showSearchHistory: false
    });
    this.onSearchConfirm();
  },

});